import Koa from "koa";
import { authRouter } from "./code/directoryInit";
import catchErr from "./code/catchERR";
import path from "node:path";
import koaStatic from 'koa-static';
import { cwd } from 'node:process';
import { historyApiFallback } from 'koa2-connect-history-api-fallback';
import koaBody from "koa-body"
import proxy from "koa-proxies";
import enforceHttps from "koa-sslify";
import https from 'https';
import fs from 'fs';

const app = new Koa()

// app.use(catchErr)
// app.use(koaBody())
// app.use(koaStatic(path.join(cwd(), 'public'), {
//     setHeaders: (res, path) => {
//         if (path.includes('uploads')) {
//             res.setHeader('Access-Control-Allow-Origin', '*')
//         }
//     }
// }))

app.use(historyApiFallback({
    index: '/index.html', whiteList: ['/api']
})).use(koaStatic(path.join(cwd(), 'dist')))

app.use(proxy('/api', {
    target: 'http://47.92.227.247:8080',
    changeOrigin: true,
    rewrite: path => path.replace(/^\/api/, ''),
    // logs: true
}))
app.use(proxy('/foo', {
    target: 'http://testapi.hbsczzxyjhhlw.cn',
    changeOrigin: true,
    rewrite: path => path.replace(/^\/foo/, ''),
    // logs: true
}))
app.use(proxy('/loa', {
    target: 'http://192.144.203.243:9999',
    changeOrigin: true,
    rewrite: path => path.replace(/^\/loa/, ''),
    // logs: true
}))
// app.use(enforceHttps())
// const options = {
//     key: fs.readFileSync('./src/ssl/baichx.shop.key'),
//     cert: fs.readFileSync('./src/ssl/baichx.shop.pem')
// };

// authRouter(app).then(() => {
//     https.createServer(options, app.callback()).listen(443, () => {
//         console.log(`应用实例，访问地址为 https://baichx.shop:443`);
//     })
// })
app.listen(80, () => {
    console.log(`应用实例，访问地址为 http://localhost:80`);
})
// authRouter(app).then(() => {
// })